﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using wsRK.AppUser;
using wsRK.Web;

namespace nkstdgia.main.membership
{
    public partial class createuser : WebPage
    {
        public bool blnIsAdministrator
        {
            get
            {
                return User.IsInRole("administrator");
            }
        }

        public string password { get { return ViewState["password"] != null ? (string)ViewState["password"] : ""; } set { ViewState["password"] = value; } }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.AssignUserToRoles_Activate();
                this.tbCreateUser.Visible = true;
                this.tbFinish.Visible = false;
            }
        }

        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            this.tbCreateUser.Visible = false;
            this.tbFinish.Visible = true;
            this.password = Password.Text;
        }

        protected void btnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipUser myObject = Membership.CreateUser(UserName.Text, this.password, Email.Text);

                if (myObject != null)
                {
                    for (int i = 0; i < AvailableRoles.Items.Count; i++)
                    {
                        if (AvailableRoles.Items[i].Selected == true)
                            Roles.AddUserToRole(UserName.Text, AvailableRoles.Items[i].Value);
                    }

                    Response.Redirect("User.aspx");
                }
            }
            catch (Exception ex)
            {
                base.showMessage(true, "OK", ex.Message);
            }
           
        }

        public void AssignUserToRoles_Activate()
        {
            List<string> lsource = RoleDataservice.getAllRoles().ToList();
            if (!User.IsInRole("administrator"))
            {
                lsource.Remove("administrator");
            }

            AvailableRoles.DataSource = lsource;
            AvailableRoles.DataBind();
            AvailableRoles.SelectedIndex = 0;
        }
    }
}